package rcs34.android.Namedays;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.GregorianCalendar;

import android.content.ContentValues;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MergeCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
  // private static final String DB_NAME =
  // DBHelper.class.getPackage().getName();
  private static final int VERSION = 4;// 3
  private final static Object MONITOR = new Object();
  // private static final String LOGTAG = DBHelper.class.getName();
  private static String[] args = new String[1];
  private static final String[] COLS = new String[] { "n" };
  private static final String TABLE = "ns";
  // private static final String TABLE_OBS = "rcs34.android.Namedays.db";
  private String name;
  
  public DBHelper(String _name) {
    super(GApp.context, _name, null, VERSION);
    name = _name;
  }
  
  @Override
  public void onCreate(SQLiteDatabase _db) {
    createStuff(_db);
  }
  
  @Override
  public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
    createStuff(db);
  }
  
  public SQLiteDatabase getReadableDatabase() {
    synchronized (MONITOR) {
      return super.getReadableDatabase();
    }
  }
  
  public SQLiteDatabase getWritableDatabase() {
    synchronized (MONITOR) {
      return super.getWritableDatabase();
    }
  }
  
  private void createStuff(SQLiteDatabase db) {
    // System.out.println("createStuff() start ...   ");
    // GApp.context.deleteDatabase(TABLE_OBS);
    Resources resources = GApp.context.getResources();
    InputStream source = null;
    if (name.equals(GApp.tableCZ)) {
      source = resources.openRawResource(R.raw.cscz);
    } else if (name.endsWith(GApp.tableDE)) {
      source = resources.openRawResource(R.raw.dede);
    } else if (name.endsWith(GApp.tableES)) {
      source = resources.openRawResource(R.raw.eses);
    } else if (name.endsWith(GApp.tableFR)) {
      source = resources.openRawResource(R.raw.frfr);
    } else if (name.endsWith(GApp.tableHU)) {
      source = resources.openRawResource(R.raw.huhu);
    } else if (name.endsWith(GApp.tableIE)) {
      source = resources.openRawResource(R.raw.enie);
    } else if (name.endsWith(GApp.tableIT)) {
      source = resources.openRawResource(R.raw.itit);
    } else if (name.endsWith(GApp.tablePL)) {
      source = resources.openRawResource(R.raw.plpl);
    } else if (name.endsWith(GApp.tableRU)) {
      source = resources.openRawResource(R.raw.ruru);
    } else if (name.endsWith(GApp.tableSK)) {
      source = resources.openRawResource(R.raw.sksk);
    } else if (name.endsWith(GApp.tableSV)) {
      source = resources.openRawResource(R.raw.svse);
    } else if (name.endsWith(GApp.tableUK)) {
      source = resources.openRawResource(R.raw.ukua);
    }
    BufferedReader r = null;
    try {
      r = new BufferedReader(new InputStreamReader(source), 8192);
      String query = "DROP TABLE IF EXISTS " + TABLE;
      db.execSQL(query);
      query = "CREATE TABLE " + TABLE + " (n TEXT NOT NULL, d TEXT NOT NULL);";
      db.execSQL(query);
      String line;
      while ((line = r.readLine()) != null) {
        line = line.trim();
        String[] aLine = line.split(",");
        // System.out.println(aLine[0]+"/ "+aLine[1]);
        if (aLine != null && aLine.length == 2) {
          ContentValues cv = new ContentValues();
          cv.clear();
          cv.put("n", aLine[0]);
          cv.put("d", aLine[1]);
          db.insertOrThrow(TABLE, null, cv);
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return;
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return;
    } finally {
      IOUtils.closeQuietly(r);
    }
    // System.out.println("createStuff() stop ...   ");
  }
  
  public Cursor findByDate(SQLiteDatabase _db, GregorianCalendar _today) {
    int month = _today.get(GregorianCalendar.MONTH) + 1;
    int day = _today.get(GregorianCalendar.DAY_OF_MONTH);
    // Hungarian support - In a leap year, names after 23.2. are one
    // day delayed
    if (GApp.isALeepYear) {
      if (month == 2 && day > 23) {
        if (name.equals(GApp.tableHU)) {
          if (day == 24) {
            day = 29;// Just an empty cursor
          } else {
            day--;
          }
        }
      }
    }
    StringBuilder sb = new StringBuilder();
    sb.append(month);
    sb.append('-');
    sb.append(day);
    args[0] = sb.toString();
    Cursor cursor = _db.query(false, TABLE, COLS, "d=?", args, null, null,
        null, null);
    // Russian support - 
    //* In a leap year some names from 12.3 are displayed 13.3.
    //* In a non-leap year some names from 29.2. go to 1.3.
    if (name.equals(GApp.tableRU) && month == 3){
      if(day == 12 || day == 13) {
        if ((day == 13) == GApp.isALeepYear) {
          args[0] = "3-13leap";
          Cursor append = _db.query(false, TABLE, COLS, "d=?", args, null, null,
              null, null);
          MergeCursor mCursor = new MergeCursor(new Cursor[] { cursor, append });
          cursor = mCursor;
        }
      }else if(day == 1 && !GApp.isALeepYear){
        args[0] = "2-29";
        Cursor append = _db.query(false, TABLE, COLS, "d=?", args, null, null,
            null, null);
        MergeCursor mCursor = new MergeCursor(new Cursor[] { cursor, append });
        cursor = mCursor;
      }
    }
    return cursor;
  }
}
